import pathlib
import json
import pandas as pd
import config.globalVariable as Gv
import api.xuangubaoApi.XgbApi as xgb
from datetime import datetime

def get_dayexpect_data():
    list = get_data()
    plate_data_all = data_conver_from(list)
    return plate_data_all

def update_hold_status(code):
    if code is None or len(code)<=0:
        return
    jsondata = get_data()
    list = jsondata[code]
    i = list[10]
    if i is not None and i == 1:
        list[10] = 0
    else:
        list[10] = 1
    jsondata[code] = list

    dayexpectfileaddr = pathlib.Path(__file__).parent.parent.resolve().as_posix() + '/' + Gv.dayexpectfileaddr
    try:
        with open(dayexpectfileaddr, 'w') as f:
            json.dump(jsondata, f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")


def get_dayexpect_emotion():
    jsondata = get_data()
    if jsondata is None or len(jsondata)<=0:
        return None,None
    # 初始化计数器
    over_3_count = 0  # “连板”前的数字大于3的总数
    under_3_count = 0  # “连板”前的数字小于3的总数
    over_3_under_expect = 0  # 大于3且“不及预期”的次数
    under_3_under_expect = 0  # 小于3且“不及预期”的次数
    over_3_probability = 0
    under_3_probability = 0
    # 遍历字典
    for _, value in jsondata.items():
        # 获取“连板”前的数字
        lianban_num = int(value[3].split('连板')[0])
        yuqi = value[8]
        if yuqi is None or len(yuqi)<=0:
            continue
        # 检查“连板”前的数字
        if lianban_num >= 3:
            over_3_count += 1
            if yuqi == Gv.dayexpectEnum.value_by_another_value(1):
                over_3_under_expect += 1
        elif lianban_num < 3:
            under_3_count += 1
            if yuqi == Gv.dayexpectEnum.value_by_another_value(1):
                under_3_under_expect += 1
    # 计算概率
    if over_3_count > 0:
        #连板'前的数字大于3时，'不及预期'出现的概率
        over_3_probability = over_3_under_expect / over_3_count * 100
    if under_3_count > 0:
        #连板'前的数字小于3时，'不及预期'出现的概率是
        under_3_probability = under_3_under_expect / under_3_count * 100
    return over_3_probability,under_3_probability

def get_data():
    dayexpectfileaddr = pathlib.Path(__file__).parent.parent.resolve().as_posix() + '/' +  Gv.dayexpectfileaddr
    jsondata = {}
    try:
        with open(dayexpectfileaddr, 'r') as f:
            jsondata = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")
    return jsondata

def clear_data():
    jsondata = None
    dayexpectfileaddr = pathlib.Path(__file__).parent.parent.resolve().as_posix() + '/' + Gv.dayexpectfileaddr
    try:
        with open(dayexpectfileaddr, 'w') as f:
            pass
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")

def data_conver_from(jsondata):
    '''每日复盘'''
    if jsondata is None or len(jsondata)<=0:
        return
    dict_columns = {0: '股票代码', 1: '股票名称', 2: '涨停时间',3:'状态',4:'实际流通',5:'主板',6:'低预期',7:'高预期',8:'预期说明',9:'预期',10:'是否持有'}
    plate_data_all = pd.DataFrame()
    sorted_data = dict(sorted(jsondata.items(), key=lambda x: sort_key(x[1])))
    # 遍历股票列表，提取数据
    for key,item in sorted_data.items():
        item_data = [
            item[0], item[1], item[2],
            item[3], item[4], item[5],item[6],item[7],item[8],item[9],item[10]
        ]
        # 将数据转换成DataFrame类型
        data = pd.DataFrame(item_data).T
        data.rename(columns=dict_columns, inplace=True)
        plate_data_all = plate_data_all._append(data, ignore_index=True)
    # 返回DataFrame类型数据
    return plate_data_all

def set_dayexpect():
    '''每日预期设置'''
    jsondata = get_data()
    if jsondata is None:
        return
    for key in jsondata:
        item = jsondata.get(key)
        if item is None:
            continue
        low = item[6]
        high = item[7]
        code = item[0]
        if code is None or len(code)<0 or low is None or len(low)<=0:
            continue
        #获取涨幅
        if code.startswith('60'):
            code = code +Gv.SS
        else:
            code = code+Gv.SZ
        resultjson = xgb.getriseData(code)
        if resultjson is None:
            continue
        resultlist = resultjson.get(code)
        if resultlist is None or len(resultlist)<3:
            continue
        rise = round(resultlist[1], 2)
        if rise < float(low):
            item[8] = Gv.dayexpectEnum.value_by_another_value(1)
        elif high is not None and len(high)>0:
            if rise <= float(high):
                item[8] = Gv.dayexpectEnum.value_by_another_value(2)
            else:
                item[8] = Gv.dayexpectEnum.value_by_another_value(3)
                if rise > float(high) + 2:
                    item[8] = Gv.dayexpectEnum.value_by_another_value(4)
        else:
            item[8] = Gv.dayexpectEnum.value_by_another_value(2)
        item[9] = str(rise)

    dayexpectfileaddr = pathlib.Path(__file__).parent.parent.resolve().as_posix() + '/' + Gv.dayexpectfileaddr
    try:
        with open(dayexpectfileaddr, 'w') as f:
            json.dump(jsondata, f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")

def sort_key(item):
    # 第四个元素中“连板”前的数字
    reboards = int(item[3].split('连板')[0]) if '连板' in item[3] else 0
    # 第六个元素：行业
    industry = item[5]
    # 第三个元素：时间
    time_str = item[2]
    # 将时间字符串转换为datetime对象以便排序
    time_obj = datetime.strptime(time_str, '%H:%M:%S')
    return (-reboards, industry, time_obj)  # 使用负号以确保连板数多的在前面

if __name__ == '__main__':
    # 让同花顺切换到688168
    #send_code_message("688168")
    plate_data_all = get_dayexpect_data()
    print(plate_data_all)
    print(Gv.dayexpectEnum.value_by_another_value(2))
